package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class FileServiceImpl implements FileService {


    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioProperties minioProperties;

    @Override
    public String upload(MultipartFile file) throws Exception {
        String bucketName = minioProperties.getBucketName();

        // 没有桶就创建
        if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        }

        minioClient.putObject(PutObjectArgs.builder()
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .object(file.getOriginalFilename())
                .bucket(bucketName)
                .build());

        // 拼接字符串，让其可以返回正确的地址
        String url = String.join("/",minioProperties.getEndpoint(),bucketName, file.getOriginalFilename());

        return url;
    }
}
